<template>
  <div class="edit-device-form">
    <div style="padding-top: 70px"></div>
    <div style="width: 50%">
      <el-form
        :model="editDialogForm"
        :rules="editDialogRules"
        ref="editDialogRules"
        label-width="120px"
        class="demo-ruleForm"
        autocomplete="off"
        disabled
      >
        <el-form-item
          label="用户头像："
          prop="pic"
          v-if="editDialogForm.title !== '修改密码'"
        >
          <el-upload
            class="avatar-uploader"
            :multiple="false"
            action="/langshi/manager/fileUpload"
            :on-preview="handlePreview"
            :on-success="handleAvatarSuccess"
            :on-remove="handleRemove"
            :data="tokenData"
            :show-file-list="false"
          >
            <img
              v-if="editDialogForm.pic"
              :src="editDialogForm.pic"
              class="avatar"
            />
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
            <div slot="tip" class="el-upload__tip">只能上传jpg/png文件</div>
          </el-upload>
        </el-form-item>
        <el-form-item
          label="用户名称："
          prop="username"
          v-if="editDialogForm.title !== '修改密码'"
        >
          <el-input
            v-model="editDialogForm.username"
            placeholder="请输入用户名，必须是3-11位之间的汉字、字母、数字、下划线"
            minlength="3"
            maxlength="11"
          ></el-input>
        </el-form-item>
        <el-form-item
          label="用户密码："
          prop="password"
          v-if="editDialogForm.title !== '修改密码' && !editDialogForm.userId"
        >
          <el-input
            v-model="editDialogForm.password"
            placeholder="请输入"
          ></el-input>
        </el-form-item>
        <el-form-item
          label="用户密码："
          v-if="editDialogForm.title !== '修改密码' && editDialogForm.userId"
        >
          <el-input
            v-model="editDialogForm.password"
            placeholder="请输入"
          ></el-input>
        </el-form-item>
        <el-form-item
          label="角色："
          prop="roleId"
          v-if="editDialogForm.title !== '修改密码' && editDialogForm.userId"
        >
          <el-select
            v-model="editDialogForm.roleId"
            placeholder="请选择"
            clearable
            filterable
            :loading="optionsData.roleLoading"
          >
            <el-option
              v-for="item in optionsData.roleList"
              :key="item.id"
              :label="item.roleName"
              :value="item.id"
            >
            </el-option>
          </el-select>
        </el-form-item>

<!--        <el-form-item-->
<!--          label="所属公司："-->
<!--          prop="company"-->
<!--          v-if="-->
<!--            editDialogForm.title !== '修改密码' &&-->
<!--            editDialogForm.roleId &&-->
<!--            editDialogForm.roleId != 1-->
<!--          "-->
<!--        >-->
<!--          <div class="global-select" >-->
<!--              <div-->
<!--                class="global-select-btn"-->
<!--                :class="{ ' global-select-btn-hover': editDialogForm.company }"-->
<!--                @click="companySearchDialog"-->
<!--              >-->
<!--                <p>-->
<!--                  {{-->
<!--                    editDialogForm.company-->
<!--                      ? editDialogForm.company.companyName-->
<!--                      : "全部公司"-->
<!--                  }}-->
<!--                </p>-->
<!--                <i class="el-icon-arrow-down global-select-icon-arrow"></i>-->
<!--                <i-->
<!--                  class="el-icon-circle-close global-select-icon-close"-->
<!--                  @click.stop="clearSearchCompany"-->
<!--                ></i>-->
<!--              </div>-->
<!--            </div>-->
<!--        </el-form-item>-->

        <el-form-item
          label="联系电话："
          prop="telephone"
          v-if="editDialogForm.title !== '修改密码'"
        >
          <el-input
            v-model="editDialogForm.telephone"
            placeholder="请输入"
          ></el-input>
        </el-form-item>

        <el-form-item label="地址：" prop="province" v-if="editDialogForm.title !== '修改密码'">
          <div>
            <el-cascader  clearable
              v-model="editDialogForm.provinceList"
              :props="{
                value: 'value',
                label: 'name',
                children: 'childrenList',
                lazy: true,
                lazyLoad: this.lazyLoad,
              }"
              style="width: 300px;"
            ></el-cascader>
          </div>
        </el-form-item>

<!--        <el-form-item-->
<!--          label="省："-->
<!--          prop="province"-->
<!--          v-if="editDialogForm.title !== '修改密码'"-->
<!--        >-->
<!--          <el-select-->
<!--            v-model="editDialogForm.province"-->
<!--            placeholder="省"-->
<!--            clearable-->
<!--            :disabled="!formData.provinceList.length"-->
<!--            @change="changeProvince"-->
<!--          >-->
<!--            <el-option-->
<!--              v-for="item in formData.provinceList"-->
<!--              :key="item"-->
<!--              :label="item"-->
<!--              :value="item"-->
<!--            >-->
<!--            </el-option>-->
<!--          </el-select>-->
<!--        </el-form-item>-->
<!--        <el-form-item-->
<!--          label="市："-->
<!--          prop="city"-->
<!--          v-if="editDialogForm.title !== '修改密码'"-->
<!--        >-->
<!--          <el-select-->
<!--            v-model="editDialogForm.city"-->
<!--            placeholder="市"-->
<!--            clearable-->
<!--            :disabled="!formData.cityList.length"-->
<!--            @change="changeCity"-->
<!--          >-->
<!--            <el-option-->
<!--              v-for="item in formData.cityList"-->
<!--              :key="item"-->
<!--              :label="item"-->
<!--              :value="item"-->
<!--            >-->
<!--            </el-option>-->
<!--          </el-select>-->
<!--        </el-form-item>-->
<!--        <el-form-item-->
<!--          label="区："-->
<!--          prop="area"-->
<!--          v-if="editDialogForm.title !== '修改密码'"-->
<!--        >-->
<!--          <el-select-->
<!--            v-model="editDialogForm.area"-->
<!--            placeholder="区"-->
<!--            clearable-->
<!--            :disabled="!formData.districtList.length"-->
<!--          >-->
<!--            <el-option-->
<!--              v-for="item in formData.districtList"-->
<!--              :key="item"-->
<!--              :label="item"-->
<!--              :value="item"-->
<!--            >-->
<!--            </el-option>-->
<!--          </el-select>-->
<!--        </el-form-item>-->

        <el-form-item
          label="详细地址："
          prop="address"
          v-if="editDialogForm.title !== '修改密码'"
        >
          <el-input id="tipinput" v-model="editDialogForm.address"></el-input>
        </el-form-item>

        <el-form-item label="">
          <el-button @click="goBack">返回 </el-button>
          <el-button
            type="primary"
            @click="handleConfirm"
            style="padding-left: 20px"
            :loading="saveLoading"
            >保存
          </el-button>
        </el-form-item>
      </el-form>
    </div>

    <el-dialog
      title="选择公司"
      :visible.sync="optionsData.companyDialog"
      center
      width="1250px"
    >
      <company-dialog
        @change="changeCompany"
        :company-data="companyData"
        v-if="optionsData.companyDialog"
      ></company-dialog>
    </el-dialog>
  </div>
</template>

<script>
import API from "@/api/apiCompanyUser";

export default {
  name: "EditDeviceForm",
  data() {
    const validateUsername = (rule, value, callback) => {
      if (!value) {
        callback(new Error("请输入用户名"));
      } else if (
        !/^[a-zA-Z0-9_\u4e00-\u9fa5]{3,11}$/.test(this.editDialogForm.username)
      ) {
        callback(new Error("输入用户名需限制在3-11位(大小写字母、数字、中文)"));
      } else {
        callback();
      }
    };
    const validateTelephone = (rule, value, callback) => {
      if (!value) {
        callback(new Error("请输入手机号"));
      } else if (!/^\d{11}$/.test(this.editDialogForm.telephone)) {
        callback(new Error("请输入正确的手机号"));
      } else {
        callback();
      }
    };
    const validatePass = (rule, value, callback) => {
      if (!value) {
        callback(new Error("请输入密码"));
      } else if (!/^[0-9A-Za-z]{6,18}$/.test(this.editDialogForm.password)) {
        callback(new Error("输入用户名需限制在6-18位且没有中文"));
      } else {
        if (this.editDialogForm.checkPassword) {
          this.$refs.editDialogRules.validateField("checkPassword");
        }
        callback();
      }
    };
    const validatePass2 = (rule, value, callback) => {
      if (!value) {
        callback(new Error("请再次输入密码"));
      } else if (value !== this.editDialogForm.password) {
        callback(new Error("两次输入密码不一致!"));
      } else {
        callback();
      }
    };
    return {
      treeList: [],
      idList: [],
      currentId: null,
      defaultProps: {
        children: "children",
        label: "label",
      },
      companyData: null,
      inputType: "text", // 含有密码输入框时需要
      // 搜索条件
      searchForm: {
        sort: 2,
        company: null,
        username: null,
        telephone: null,
        roleId: null,
      },
      // 表格相关
      isIndeterminate: false,
      checkAll: false,
      multipleSelection: [], // 多选
      editDialog: false, // 编辑弹窗
      editCloseIcon: false, // close展示
      editCloseColor: false, // close展示
      // 编辑弹窗表单
      editDialogForm: {
        title: "新增用户",
        userId: null,
        username: null,
        password: null,
        telephone: null,
        company: null,
        checkPassword: null,
        roleId: null,
        pic: "~images/headPic.png",
        address: "",
        province: "",
        city: "",
        area: "",
        provinceList: []
      },
      editDialogRules: {
        // 编辑弹窗表单验证
        telephone: [
          { required: true, validator: validateTelephone, trigger: "blur" },
        ],
        username: [
          { required: true, validator: validateUsername, trigger: "blur" },
        ],
        company: [{ required: true, message: "请选择公司", trigger: "change" }],
        password: [
          { required: true, validator: validatePass, trigger: "blur" },
        ],
        checkPassword: [
          { required: true, validator: validatePass2, trigger: "blur" },
        ],
        roleId: [{ required: true, message: "请选择角色", trigger: "change" }],
      },
      // 下拉框列表
      optionsData: {
        companyDialogType: null, // 1 - 筛选弹窗 2 - 编辑弹窗
        companyDialog: false,
        roleLoading: true,
        roleList: [],
      },
      // 表格相关
      tableLoading: false,
      dataList: [],
      pageSize: 10,
      pageNum: 1,
      total: 0,
      pageSizes: [10, 20, 50, 100],
      // 权限弹窗
      permissionDialog: false,
      permissionList: [],
      tokenData: {
        token: "",
      },
      headPic: "",
      province: [],
      formData: {
        provinceList: [],
        cityList: [],
        districtList: [],
      },
      saveLoading: false,
      props: {
        lazy: true,
        lazyLoad: this.lazyLoad,
        children: 'childrenList',
      },
    };
  },
  watch: {
    $route(){
      this.tokenData.token = this.$store.state.token;
      this.getRoleList();
      // this.getProvince();
      if (this.$route.query.row) {
        let row = JSON.parse(this.$route.query.row);
        this.editDialogForm = {
          title: "编辑用户",
          userId: row.id,
          username: row.username,
          telephone: row.telephone,
          company: {
            companyName: row.company_name,
            id: row.company_id,
          },
          roleId: row.user_type,
          address: row.address,
          province: row.province,
          city: row.city,
          area: row.area,
          pic: row.pic,
          password: "",
          provinceList: []
        };
        let provinceList = []
        provinceList.push(row.province)
        provinceList.push(row.city)
        provinceList.push(row.area)
        this.editDialogForm.provinceList = provinceList
        // this.getCity();
        // this.getDistrict();
      } else if (this.$route.query.type && this.$route.query.type == 1) {
        this.getUserMsg();
      } else {
        this.addUser();
      }
    }
  },
  activated() {
    this.saveLoading = false
    this.tokenData.token = this.$store.state.token;
    this.getRoleList();
    // this.getProvince();
    if (this.$route.query.row) {
      let row = JSON.parse(this.$route.query.row);
      this.editDialogForm = {
        title: "编辑用户",
        userId: row.id,
        username: row.username,
        telephone: row.telephone,
        company: {
          companyName: row.company_name,
          id: row.company_id,
        },
        roleId: row.user_type,
        address: row.address,
        province: row.province,
        city: row.city,
        area: row.area,
        pic: row.pic,
        password: "",
        provinceList: []
      };
      let provinceList = []
      provinceList.push(row.province)
      provinceList.push(row.city)
      provinceList.push(row.area)
      this.editDialogForm.provinceList = provinceList
      // this.getCity();
      // this.getDistrict();
    } else if (this.$route.query.type && this.$route.query.type == 1) {
      this.getUserMsg();
    } else {
      this.addUser();
    }
  },
  methods: {
    lazyLoad(node, resolve) {
      let that = this
      setTimeout(() => {
        that.getProvince(node, resolve)
      }, 100)
    },
    // 获取省市区
    getProvince(node,resolve){
      console.log(node)
      console.log("-------------",node.level)
      if(node.level == 0){
        let params = {
          token: this.$store.state.token,
        };
        API.get_province(params).then((res) => {
          if (res.key === 1000) {
            var list = res.result.list
            var provinceList = []
            list.forEach((item) => {
              var obj = {
                name: item,
                label: item,
                value: item,
                loading: false,
                childrenList: [],
                type: 1,
              }
              provinceList.push(obj)
            })
            resolve(provinceList)
          }
        });
      }else if(node.level == 1){
        let params = {
          token: this.$store.state.token,
          province: node.label
        };
        API.get_city(params).then((res) => {
          if (res.key === 1000) {
            let arr = [];
            if (res.result.list) {
              res.result.list.forEach((it) => {
                arr.push({
                  label: it,
                  value: it,
                  name: it,
                  loading: false,
                  childrenList: [],
                });
              });
            }
            resolve(arr)
          }
        });
      }else if(node.level == 2){
        let params = {
          token: this.$store.state.token,
          city: node.label
        };
        API.get_district(params).then((res) => {
          if (res.key === 1000) {
            let arr = [];
            if (res.result.list) {
              res.result.list.forEach((it) => {
                arr.push({
                  label: it,
                  value: it,
                  name: it,
                  loading: false,
                  //这句代码表示当点击最后一级的时候 label后面不会转圈圈 并把相关值赋值到选择器上
                  leaf: node.level >= 1,
                });
              });
            }
            resolve(arr)
          }
        });
      }
    },
    getUserMsg() {
      this.$bus.$emit("show-loading", true);
      const params = {
        token: this.$store.state.token,
      };
      API.getManagerUserMsg(params).then((res) => {
        if (res.key === 1000) {
          res = res.result.data;
          let row = res;
          this.editDialogForm = {
            title: "编辑用户",
            userId: row.id,
            username: row.username,
            telephone: row.telephone,
            company: {
              companyName: row.company_name,
              id: row.company_id,
            },
            roleId: row.user_type,
            address: row.address,
            province: row.province,
            city: row.city,
            area: row.area,
            pic: row.pic,
            provinceList: []
          };
          let provinceList = []
          provinceList.push(row.province)
          provinceList.push(row.city)
          provinceList.push(row.area)
          this.editDialogForm.provinceList = provinceList
          this.getCity();
          this.getDistrict();
        }
        this.$bus.$emit("show-loading", false);
      });
    },
    // changeCompany(company) {
    //   if (this.optionsData.companyDialogType === 1) {
    //     this.optionsData.companyDialog = false;
    //     this.searchForm.company = company;
    //   } else if (this.optionsData.companyDialogType === 2) {
    //     this.optionsData.companyDialog = false;
    //     this.editDialogForm.company = company;
    //     this.$refs.editDialogRules.validateField("company");
    //   }
    // },
    editLeave() {
      this.editCloseIcon = false;
      this.editCloseColor = false;
    },
    editEnter() {
      if (this.editDialogForm.company) {
        this.editCloseIcon = true;
        this.editCloseColor = true;
      }
    },
    companyEditDialog() {
      // 打开编辑弹窗
      this.companyData = this.editDialogForm.company;
      this.optionsData.companyDialogType = 2;
      this.optionsData.companyDialog = true;
    },
    getRoleList() {
      const params = {
        token: this.$store.state.token,
      };
      API.getAllRoleList(params).then((res) => {
        if (res.key === 1000) {
          this.optionsData.roleLoading = false;
          this.optionsData.roleList = res.result.list;
        }
      });
    },
    //返回
    goBack() {
      this.$router.go(-1);
    },
    // 防止密码自动输入
    changeInputType() {
      this.inputType = "password";
    },
    changeProvince() {
      if (this.editDialogForm.city) {
        this.editDialogForm.city = null;
      }
      if (this.editDialogForm.area) {
        this.editDialogForm.area = null;
      }
      this.formData.cityList = [];
      this.formData.districtList = [];
      this.getCity();
    },
    changeCity() {
      if (this.editDialogForm.area) {
        this.editDialogForm.area = null;
      }
      this.formData.districtList = [];
      this.getDistrict();
    },
    // getProvince() {
    //   this.$bus.$emit("show-loading", true);
    //   const params = {
    //     token: this.$store.state.token,
    //   };
    //   API.get_province(params).then((res) => {
    //     if (res.key === 1000) {
    //       res = res.result.list;
    //       this.formData.provinceList = res;
    //     }
    //     this.$bus.$emit("show-loading", false);
    //   });
    // },
    getCity() {
      this.$bus.$emit("show-loading", true);
      const params = {
        token: this.$store.state.token,
        province: this.editDialogForm.province,
      };
      API.get_city(params).then((res) => {
        if (res.key === 1000) {
          res = res.result.list;
          this.formData.cityList = res;
        }
        this.$bus.$emit("show-loading", false);
      });
    },
    getDistrict() {
      this.$bus.$emit("show-loading", true);
      const params = {
        token: this.$store.state.token,
        province: this.editDialogForm.province,
        city: this.editDialogForm.city,
      };
      API.get_district(params).then((res) => {
        if (res.key === 1000) {
          res = res.result.list;
          this.formData.districtList = res;
        }
        this.$bus.$emit("show-loading", false);
      });
    },
    handleRemove(file, fileList) {
      console.log(file, fileList);
    },
    handleAvatarSuccess: function (e) {
      if (e.key == 1000) {
        this.editDialogForm.pic = e.result.data.path;
        // this.headPic = e.result.data.path;
        this.$message.success({
          showClose: true,
          message: "上传成功",
          duration: 1500,
        });
      }
    },
    handlePreview(file) {
      console.log(file);
    },
    // 新增用户按钮
    addUser() {
      this.editDialogForm = {
        title: "新增用户",
        userId: null,
        username: null,
        telephone: null,
        company: null,
        roleId: null,
        pic: "https://abc.landseabespoke.com/pic.svg",
        address: "",
        province: "",
        city: "",
        area: "",
      };
      this.getProvince();
      this.$nextTick(() => {
        this.$refs.editDialogRules.clearValidate();
      });
      this.editDialog = true;
    },
    // 编辑用户信息接口
    handleConfirm() {
      this.$refs.editDialogRules.validate((valid) => {
        if (!valid) return;
        if (this.editDialogForm.title === "修改密码") {
          if (!this.editDialogForm.userId) {
            this.$message({
              type: "success",
              message: "操作失败，请刷新页面后重试",
            });
            return
          }
          this.saveLoading = true
          this.handleChangePassword();
        } else {
          this.saveLoading = true
          this.handleEdit();
        }
      });
    },
    handleEdit() {
      this.$bus.$emit("show-loading", true);
      const params = {
        title: this.editDialogForm.title,
        userId: this.editDialogForm.userId,
        username: this.editDialogForm.username,
        telephone: this.editDialogForm.telephone,
        roleId: this.editDialogForm.roleId,
        address: this.editDialogForm.address,
        province: this.editDialogForm.provinceList[0],
        city: this.editDialogForm.provinceList[1],
        area: this.editDialogForm.provinceList[2],
        pic: this.editDialogForm.pic,
        realname: this.editDialogForm.realname,
        id: this.editDialogForm.id,
      }
      params.token = this.$store.state.token;
      params.realname = params.username;
      if (this.editDialogForm.userId) {
        params.id = this.editDialogForm.userId;
      }

      params.password = this.editDialogForm.password;
      if (this.editDialogForm.roleId) {
        params.roleId = this.editDialogForm.roleId
      }
      if (this.editDialogForm.company && this.editDialogForm.company.id) {
        params.companyId = this.editDialogForm.company.id;
      } else {
        params.companyId = 0;
      }
      API.add_normal_user_my(params).then((res) => {
        if (res.key === 1000) {
          if (this.editDialogForm.userId) {
            this.$message({
              type: "success",
              message: "编辑用户成功",
            });
            localStorage.setItem("editUserType", 2);
          } else {
            this.$message({
              type: "success",
              message: "新增用户成功",
            });
            localStorage.setItem("editUserType", 1);
          }
          this.$router.go(-1);
          this.editDialog = false;
        }
        this.saveLoading = false;
        this.$bus.$emit("show-loading", false);
      });
    },
    handleChangePassword() {
      this.$bus.$emit("show-loading", true);
      const params = {
        token: this.$store.state.token,
        password: this.editDialogForm.password,
        userId: this.editDialogForm.userId,
      };
      API.changePassword(params).then((res) => {
        if (res.key === 1000) {
          this.editDialog = false;
          this.$message({
            type: "success",
            message: "修改密码成功",
          });
          this.saveLoading = false
          this.$router.go(-1);
        }
        this.$bus.$emit("show-loading", false);
      });
    },
    // 编辑弹窗关闭
    handleEditDialogClose() {
      this.editDialog = false;
      this.$refs.editDialogRules.resetFields();
    },


    // 公司弹窗
    changeCompany(company) {
      this.optionsData.companyDialog = false;
      this.editDialogForm.company = company;
      this.$refs.editDialogRules.validateField("company");
    },
    companySearchDialog() {
      // 打开搜索栏弹窗
      this.companyData = this.editDialogForm.company;
      this.optionsData.companyDialog = true;
    },
    clearSearchCompany() {
      // 清除搜索栏公司信息
      this.editDialogForm.company = null;
    },
  },
};
</script>

<style lang="sass">
.avatar-uploader
  .el-upload
    border: 1px dashed #d9d9d9
    border-radius: 6px
    cursor: pointer
    position: relative
    overflow: hidden
    &:hover
      border-color: #409eff
      .avatar-uploader-icon
        font-size: 28px
        color: #8c939d
        width: 100px
        height: 100px
        line-height: 100px !important
        text-align: center
      .avatar
        width: 100px
        height: 100px
        display: block
.edit-device-form
  .global-select-btn
    background: #F4F6F9
    border: none
</style>
<style lang="sass" scoped>
.edit-device-form
  @include container
  box-shadow: 0px 0px 10px 0px rgba(93, 139, 198, 0.05)
  border-radius: 14px
.global-form-dialog
  .el-dialog__body
    padding: 30px 50px

.map-container
  display: flex
  .amap-wrapper2
    width: 550px
    height: 500px
    margin-right: 24px
  .map-list
    width: 300px
    height: 500px
    overflow-y: auto
    .map-item
      cursor: pointer
      margin-bottom: 15px
      padding: 6px
      border-radius: 4px
      &.active
        background: $main-color
        color: #fff
      &:last-child
        margin-bottom: 0
      p
        line-height: 22px
</style>
